import { Picker, View } from "@tarojs/components";
import { Paragraph, SelectionContainer } from "@/components";
import { useEffect, useMemo, useState } from "react";
import { convertTimeToAmPm, formatDateString } from "@/utils";
import { useUserInfo } from "@/store/userDataContext";
import { DateShape, TimeShape } from "@/data/shared/timeTypes";
import style from "./index.module.scss";
import { colors } from "@/data/shared/colors";

export type CourseEventReferenceShape = {
  schedulingId: number;
  schedulingDate: DateShape;
  languageName: string;
  schedulingStartTime: TimeShape;
  schedulingEndTime: TimeShape;
  remainingSeatCount: number;
  courseId?: number;
  price?: number;
};

// Inline component
const PickerTimeDisplay = ({
  upperText,
  lowerLeftText,
  lowerRightText,
  type = "default",
}: {
  upperText: string;
  lowerLeftText: string;
  lowerRightText: string;
  type?: "default" | "non-selected";
}) => {
  const textColor = type === "default" ? colors.colorDark : colors.colorGrey;

  return (
    <View className={style["event-selection"]}>
      <Paragraph size="small" color={textColor} noSpacing>
        {upperText}
      </Paragraph>
      <View
        className={`
          ${style["event-selection--lower-text"]}
          ${style["event-selection--lower-text__left"]}`}
      >
        <Paragraph size="small" color={textColor} noSpacing>
          {lowerLeftText}
        </Paragraph>
      </View>
      <View
        className={`
          ${style["event-selection--lower-text"]}
          ${style["event-selection--lower-text__right"]}
        `}
      >
        <Paragraph size="small" noSpacing color={textColor}>
          {lowerRightText}
        </Paragraph>
      </View>
    </View>
  );
};

export type CombinedBookingIds = `${number}-${number}`;

interface PickerGroupProps {
  combinedBookingId: CombinedBookingIds;
  // Remap data to avoid dealing with type inference
  eventData: CourseEventReferenceShape[];
  type: "course" | "bundlecourse";
  discoverySeriesSpacing?: boolean;
}

const ALL_LANGUAGES_TAG = "所有语言";

export const C08CoursePickerGroup = ({
  eventData,
  combinedBookingId,
  type,
  discoverySeriesSpacing = false,
}: PickerGroupProps) => {
  const { userInfoState, dispatchUserDataAction } = useUserInfo();
  const [selectedLanguage, setSelectedLangage] = useState(ALL_LANGUAGES_TAG);

  const [selectedIndex, setSelectedIndex] = useState<null | number>(null);

  const primaryOptionsExtended = useMemo(
    () => [
      ALL_LANGUAGES_TAG,
      ...new Set(eventData.map((item) => item.languageName)),
    ],
    [eventData]
  );

  const filteredData = useMemo(() => {
    return (
      eventData.filter((occation) => {
        return (
          selectedLanguage === ALL_LANGUAGES_TAG ||
          selectedLanguage === occation.languageName
        );
      }) ?? []
    );
  }, [eventData, selectedLanguage]);

  // Initial and future setting of global state
  useEffect(() => {
    if (filteredData && selectedIndex !== null) {
      dispatchUserDataAction({
        type: "COURSE_EVENT_SELECT",
        data: {
          bookingId: combinedBookingId,
          type,
          bookingData: filteredData[selectedIndex],
        },
      });
    } else {
      dispatchUserDataAction({
        type: "COURSE_EVENT_SELECT",
        data: null,
      });
    }
  }, [selectedIndex, selectedLanguage]);

  const onLanguageChange = (e) => {
    setSelectedIndex(0);
    setSelectedLangage(primaryOptionsExtended[e.detail.value]);
  };

  const onFilteredChange = (e) => {
    setSelectedIndex(e.detail.value);
  };

  const displayEventData = userInfoState.selectedCourseData[combinedBookingId];

  return (
    <View
      className={`${style["picker-element-wrapper"]} ${
        discoverySeriesSpacing ? style["discovery-series-spacing"] : null
      }`}
    >
      <>
        <Picker
          className={style["picker-element"]}
          mode="selector"
          range={primaryOptionsExtended}
          onChange={onLanguageChange}
        >
          <SelectionContainer>
            <Paragraph size="small" color={colors.colorDark} noSpacing>
              {selectedLanguage}
            </Paragraph>
          </SelectionContainer>
        </Picker>

        <Picker
          mode="selector"
          range={filteredData.map((event) => {
            return `${formatDateString(
              event.schedulingDate
            )} / ${convertTimeToAmPm(
              event.schedulingStartTime
            )} - ${convertTimeToAmPm(event.schedulingEndTime)} | ${
              event.languageName
            }`;
          })}
          onChange={onFilteredChange}
        >
          <SelectionContainer>
            <PickerTimeDisplay
              type={displayEventData ? "default" : "non-selected"}
              upperText={
                displayEventData
                  ? formatDateString(displayEventData.schedulingDate)
                  : "请选择时间"
              }
              lowerLeftText={
                displayEventData
                  ? `${convertTimeToAmPm(
                      displayEventData.schedulingStartTime
                    )} - ${convertTimeToAmPm(
                      displayEventData.schedulingEndTime
                    )}`
                  : `下一堂：${
                      filteredData.length
                        ? formatDateString(filteredData[0].schedulingDate)
                        : "无"
                    }`
              }
              lowerRightText={
                displayEventData
                  ? `仅剩${displayEventData.remainingSeatCount}个席位`
                  : ""
              }
            />
          </SelectionContainer>
        </Picker>
      </>
    </View>
  );
};
